#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import json
import time
import sys

if __name__ == '__main__':
    socket_ip = '127.0.0.1'
    socket_port = 60826
    thread_flag = True
    dstSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    dstSocket.connect((socket_ip, socket_port))
    print("start data process node...", thread_flag, "\n")
    index = 0
    pulse = 1
    json_file = "/home/gj/Download/panosim_flow1.json"
    while thread_flag:
        with open(json_file) as f:
            while True:
                start = time.time()
                linestr = f.readline()
                if linestr:
                    dataPackage = json.loads(linestr)
                    if dataPackage:
                        data = {}
                        data["globalTimeStamp"] = dataPackage["globalTimeStamp"]
                        data["participantNum"] = dataPackage["participantNum"]
                        data["e1FrameParticipant"] = []
                        for i in range(dataPackage["participantNum"]):
                            data["e1FrameParticipant"].append({
                                "id": dataPackage["e1FrameParticipant"][i]["id"],
                                "vehicleType": dataPackage["e1FrameParticipant"][i]["vehicleType"],
                                "x": dataPackage["e1FrameParticipant"][i]["x"]+224.58,
                                "y": 207.37 - dataPackage["e1FrameParticipant"][i]["y"],
                                "speed": dataPackage["e1FrameParticipant"][i]["speed"],
                                "courseAngle": dataPackage["e1FrameParticipant"][i]["courseAngle"]
                            })
                        try:
                            sendData = json.dumps(data).encode('utf8')
                            dstSocket.send(sendData)
                        except:
                            print('dst Socket is closed!!')
                        index = index + 1
                        print(index)
                        end = time.time()
                        if pulse > (end - start):
                            time.sleep(pulse - (end - start))
                        # tick = tick + pulse